<template>
  <div style="margin-top: 10px">
    <el-tag type="primary">我的购物车</el-tag>
    <div style="float: right;margin: 10px">
      <el-input
          style="width: 280px"
          placeholder="请输入商品名称"
          suffix-icon="el-icon-search"
          v-model="name"
      ></el-input>
      <el-button class="ml-5" type="primary" @click="load"
      >搜索
      </el-button
      >
      <el-button type="warning" @click="reset">重置</el-button>
    </div>
    <el-table :data="tableData" :row-class-name="tableRowClassName" @row-click="onRowClick" stripe style="width: 100%">
      <el-table-column
          label="序号"
          type=index
          width="55">
      </el-table-column>
      <el-table-column label="商品图片" prop="simage">
        <template slot-scope="scope">
          <el-image :src="tableData[scope.$index].simage"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="sname" label="商品名称"></el-table-column>
      <el-table-column prop="sprices" label="单价"></el-table-column>
      <el-table-column prop="sdiscount" label="优惠"></el-table-column>
      <el-table-column label="商家" prop="sproducer"></el-table-column>
      <el-table-column label="购买数量" width="150">
        <template slot-scope="scope">
          <el-input-number v-model="nums[scope.$index]" :min="0" :max="10" label="购买数量" style="width: 100px"
                           @change="changeCount(scope.$index)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="购买鞋码" width="150">
        <template slot-scope="scope">
          <el-tag type="primary">{{ sizes[scope.$index] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="200">
        <template slot-scope="scope">
          <el-button type="danger" icon="el-icon-delete" circle @click="del(tableData[scope.$index].sid)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 10px">
      <div style="display: flex; background-color: white; padding: 10px">
        <div style="flex: 1; padding-left: 20px; color: #999; font-size: 12px">
          <div>共 <span style="color: red; font-size: 20px">{{ count }}</span> 件商品</div>
          <div style="color: orange; padding-top: 5px">立即下单，享超值优惠！</div>
        </div>
        <div style="flex: 1;color: red; text-align: right">
          <!--    如果总价为0 不显示-->
          <span v-if="totalPrice==0.00">
          <el-button @click="load">查看实际付款：</el-button>
        </span>
          <div v-else>
            <span>总价：</span>
            <span>￥ {{ totalPrice }}</span>
            <el-button style="background-color: red; color: white; margin-left: 20px" @click="submitOrder">去结算
            </el-button>
          </div>
          <div style="text-align: right; color: #999; font-size: 12px; margin-right: 85px">
            已优惠： - ￥{{ totaldiscount }}
          </div>
        </div>
      </div>
      <div style="padding: 10px 0">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[1,2,5,10]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: "FrontCart",
  data() {
    return {
      user: {},
      name: "",
      nums: [],
      sizes: [],
      pageNum: 1,
      pageSize: 5,
      total: 0,
      tableData: [],
      count: 0,
      totalPrice: 0,
      totaldiscount: 0
    }
  },
  created() {
    this.user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
    this.load()
  },
  methods: {
    load() {
      if (!this.user.uid) {
        this.$message({
          type: 'warning',
          message: '请登录！'
        })
        return
      }
      axios.get("/shoppingcart/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
          uid: this.user.uid
        }
      }).then(res => {
        if (res.data.code === 201) {
          this.$message({
            type: "warning",
            message: res.data.msg,
            duration: 1000
          })
        } else {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          this.nums = res.data.data2[0]
          // console.log(res.data)
          // console.log(this.nums)
          this.sizes = res.data.data2[1]
          console.log("this.sizes"+this.sizes)
        }
      })
      this.getTotalPrice()
      this.getcount()
      this.gettotaldiscount()
    },
    submitOrder() {
      if (!this.tableData.length) {
        this.$message({
          type: 'warning',
          message: '您还未选择商品'
        })
        return
      }
      localStorage.setItem("tableData", JSON.stringify(this.tableData))
      this.$router.push({
        path: "/front/preOrder",
        query: {
          //tableData传参一刷新数据就变成object，不好
          totalPrice: this.totalPrice,
          totaldiscount: this.totaldiscount,
          nums: this.nums,
          sizes: this.sizes,
          //tableData: this.tableData
        }
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    tableRowClassName({row, rowIndex}) {
      row.row_index = rowIndex;
    },
    onRowClick(row, event, column) {
      this.currentRowIndex = row.row_index;
    },
    reset() {
      this.name = "";
      this.load();
    },
    changeCount(index) {
      console.log(index)
      axios.post("/shoppingcart/update?uid=" + this.user.uid + "&sid=" + this.tableData[index].sid + "&scount=" + this.nums[index])
      this.getTotalPrice()
      this.getcount()
      this.gettotaldiscount()
    },
    gettotaldiscount() {
      //总计
      let dis = 0;
      this.tableData.forEach((item, index) => {
        dis += (item.sdiscount) * this.nums[index]
      })
      this.totaldiscount = dis.toFixed(2);
    },
    getcount() {
      //总计
      let cot = 0;
      this.nums.forEach((item, index) => {
        cot += item
      })
      this.count = cot
    },
    getTotalPrice() {
      //总计
      let price = 0;
      this.tableData.forEach((item, index) => {
        price += (item.sprices - item.sdiscount) * this.nums[index]
      })
      this.totalPrice = price.toFixed(2);
    },
    del(sid) {
      let uid = this.user.uid
      axios.get("/shoppingcart/delete?uid=" + uid + "&sid=" + sid).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.msg)
          this.load()
        } else {
          this.$message.error("出错")
        }
      })
    },
  }
}
</script>

<style scoped>

</style>